package com.ruoyi.web.controller.user;

import com.aliyun.dypnsapi20170525.models.SendSmsVerifyCodeResponse;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.RandomUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sms")
public class UserSmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate redisTemplate;

    // 短信验证码缓存键前缀
    private static final String SMS_CODE_KEY = "sms_code:";
    // 验证码过期时间（分钟）
    private static final Integer SMS_CODE_EXPIRATION = 5;

    @PostMapping("/send/message/{phoneNumber}")
    public AjaxResult sendMessage(@PathVariable String phoneNumber) {

        try {
            // 构建Redis缓存键
            String cacheKey = SMS_CODE_KEY + phoneNumber;

            // 先从Redis中获取验证码
            Object cachedCode = redisTemplate.opsForValue().get(cacheKey);
            String verifyCode = null;

            if (cachedCode != null) {
                verifyCode = cachedCode.toString();
            }

            // 如果Redis中没有验证码，则生成新的验证码
            if (StringUtils.isEmpty(verifyCode)) {
                verifyCode = RandomUtil.getSixBitRandom();

                // 将验证码存入Redis，设置过期时间为5分钟
                redisTemplate.opsForValue().set(cacheKey, verifyCode, SMS_CODE_EXPIRATION, TimeUnit.MINUTES);
            }

            // 发送短信验证码
            SendSmsVerifyCodeResponse response = smsService.sendVerifyCode(phoneNumber, verifyCode, "5");

            return AjaxResult.success("短信发送成功", response);

        } catch (Exception e) {
            return AjaxResult.error("短信发送失败: " + e.getMessage());
        }
    }
}
